package com.education.business.utils;

import cn.hutool.core.date.DateUtil;
import com.education.common.constants.SystemConstants;
import com.education.common.exception.BusinessException;
import com.education.common.template.BaseTemplate;
import com.education.common.template.EnjoyTemplate;
import com.education.common.utils.FileUtils;
import com.education.common.utils.HtmlUtil;
import com.education.common.utils.SpellUtils;
import com.education.model.entity.CourseInfo;
import com.education.model.entity.OrgInfoEntity;
import com.education.model.entity.StudentInfo;
import com.jfinal.kit.Kv;


import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.UUID;

public class CertUtil {

    /**
     * 构建证书
     * @param courseName 课程名称
     * @param courseName 课程名称
     * @param studentInfo 学生信息
     * @param orgName 机构
     *
     * @return
     * @throws IOException
     */
    public static String generateCert(String courseName, StudentInfo studentInfo, String orgName,String scoreLevel) {
        try {
            //  唯一证书编号生成
            String certCode = "No." + UUID.randomUUID().toString().replace("-", "");
            Kv data = Kv.create().set("certCode", certCode)
                    .set("studentName",studentInfo.getName())
                    .set("studentNumber",studentInfo.getId())
                    .set("orgName",orgName)
//                    .set("publishTime", DateUtil.format(new Date(),  "yyyy年MM月dd日 HH时mm分ss秒"))
                    .set("publishTime", DateUtil.format(new Date(),  "yyyy-MM-dd"))
                    .set("grantOrg",orgName)
                    .set("scoreLevel",scoreLevel);

            String fileName = SpellUtils.getSpell(studentInfo.getName() + courseName);

            String htmlName = fileName + ".html";

//            String outDirPath = "/images/cer/" + certCode;
            String outDirPath = "/cer/" + certCode;
            String paperTemplateSavePath = FileUtils.getUploadPath() + outDirPath;
            BaseTemplate template = new EnjoyTemplate(SystemConstants.CER_TEMPLATE, paperTemplateSavePath);
            template.generateTemplate(data, htmlName);

            // 将html转为pdf
            String pdfName = fileName + ".pdf";
            HtmlUtil.html2pdf(paperTemplateSavePath + "/" + htmlName, paperTemplateSavePath + "/" + pdfName);
            return outDirPath + "/" + pdfName;
        } catch (Exception e) {
            throw new BusinessException("证书构建失败："+e.getMessage());
        }

    }
}
